package com.primeton.poctag.service.warn;

import com.alibaba.fastjson.JSONObject;
import com.primeton.poctag.configure.WarnProperties;
import com.primeton.poctag.util.RestApiUtils;
import com.primeton.poctag.util.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 告警服务， 可以实现持久化到数据库中，或者发送其他警告消息。 默认只打印日志
 *
 * <pre>
 *
 * Created by zhaopx.
 * User: zhaopx
 * Date: 2019/4/4
 * Time: 09:56
 *
 * </pre>
 *
 * @author zhaopx
 */
@Component("warnService")
public class WarnServiceImpl implements WarnService,
        InitializingBean, DisposableBean {


    /**
     * 调度引擎预警类型
     */
    public final static String DING_MESSAGE_TYPE_BATCH_SCHEDULER = "BATCH_SCHEDULE_ALARM";


	private static Logger logger = LoggerFactory.getLogger(WarnServiceImpl.class);


	@Autowired
    WarnProperties warnProperties;



    @Override
    public void afterPropertiesSet() throws Exception {
    }


    @Override
    public synchronized Map<String, Object> warn(WarnMessage warnMessage) {
        String message = null;
        try {
            JSONObject msg = new JSONObject();
            msg.put("type", DING_MESSAGE_TYPE_BATCH_SCHEDULER);
            msg.put("content", warnMessage.getWarnSubtext() + ": " + warnMessage.getWarnContent());
            msg.put("smsLenvel", 1);
            msg.put("sendTime", System.currentTimeMillis());
            RestApiUtils.post(warnProperties.getUrl(), msg);
            logger.warn("发生警告： " + msg);
            return msg;
        } catch (Exception e) {
            message = e.getMessage();
        	logger.warn("调用告警服务异常。ERROR:" + warnProperties.getUrl(), e);
        }
        Map<String, Object> r = new HashMap<>();
        r.put("success", false);
        r.put("message", message);
        return r;
    }


    @Override
    public void destroy() throws Exception {
    }


    public String getUrl() {
        return warnProperties.getUrl();
    }


    @Override
    public long getWarnJobTimeout() {
        // 是否开启任务预警
        return  (isWarnEnable() ? TimeUtils.getTime(warnProperties.getWarnJobTimeout()) : -1);
    }

    @Override
    public long getWarnJobPeriod() {
        return  (isWarnEnable() ? TimeUtils.getTime(warnProperties.getWarnJobPeriod()) : -1);
    }

    @Override
    public boolean isWarnEnable() {
        return warnProperties.isWarnEnable();
    }
}
